package com.zlll.winner.service.area;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zlll.winner.business.model.area.AreaCity;
import com.zlll.winner.business.vo.area.CityTree;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.mapper.area.AreaCityMapper;
import com.zlll.winner.business.service.area.IAreaCityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qsx
 * @since 2019-09-10
 */
@Service
public class AreaCityServiceImpl extends ServiceImpl<AreaCityMapper, AreaCity> implements IAreaCityService {

    @Autowired
    private AreaCityMapper areaCityMapper;

    /**
     * 构建城市树
     * @return
     */
    @Override
    public List<CityTree> getCityListTree() {
        List<CityTree> tree = new ArrayList<>();
        List<AreaCity> list = this.getAllList();
        list.stream().filter(cityTree -> cityTree.getPId().intValue()==0).forEach(cityTree ->{
            CityTree treeVo = new CityTree();
            BeanUtils.copyProperties(cityTree,treeVo);
            //递归调用构建children
            createCityTree(treeVo,list);
            tree.add(treeVo);
        });
        return tree;
    }

    /**
     * 获取所有的城市信息
     * @return
     */
    public List<AreaCity> getAllList(){
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", CommonEnum.DelEnum.UNDEL.val());
        return areaCityMapper.selectList(queryWrapper);
    }

    @Override
    public String getCityCode(String cityName) {
        QueryWrapper<AreaCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", CommonEnum.DelEnum.UNDEL.val());
        queryWrapper.eq("name",cityName);
        List<AreaCity> cityList = areaCityMapper.selectList(queryWrapper);
        if (cityList.size()>0){
            return cityList.get(0).getCode();
        }
        return null;
    }

    /**
     * 递归构建项目树
     * @param parent
     * @param allList
     */
    private void createCityTree(CityTree parent,List<AreaCity> allList){
        List<AreaCity> childList = allList.stream().filter(projectTree -> projectTree.getPId().equals(parent.getId())).collect(Collectors.toList());
        if(childList != null && childList.size() > 0){
            List<CityTree> children = new ArrayList<>(childList.size());
            childList.forEach(projectTree -> {
                CityTree projectTreeVo = new CityTree();
                BeanUtils.copyProperties(projectTree,projectTreeVo);
                createCityTree(projectTreeVo,allList);
                children.add(projectTreeVo);
            });
            parent.setChildren(children);
            parent.setHasChild(true);
        }
    }
}
